# frozen_string_literal: true

module VulnerabilityIssueLinks
  class BulkCreateService < BaseService
    def initialize(user, issue, vulnerabilities)
      @user = user
      @issue = issue
      @vulnerabilities = vulnerabilities
    end

    def execute
      return ServiceResponse.error(message: "No Vulnerabilities given") unless @vulnerabilities
      return ServiceResponse.error(message: "No Issue given") unless @issue

      attributes = issue_links_attributes(@issue, @vulnerabilities)
      issue_links = bulk_insert_issue_links(attributes)

      ServiceResponse.success(
        payload: { issue_links: issue_links }
      )
    end

    private

    def issue_links_attributes(issue, vulnerabilities)
      vulnerabilities.map do |vulnerability|
        {
          vulnerability_id: vulnerability.id,
          issue_id: issue.id,
          link_type: ::Vulnerabilities::IssueLink.link_types[:related],
          created_at: Time.zone.now,
          updated_at: Time.zone.now
        }
      end
    end

    def bulk_insert_issue_links(attrs)
      result = ::Vulnerabilities::IssueLink.upsert_all(
        attrs,
        unique_by: %i[vulnerability_id issue_id],
        returning: %i[id]
      )
      ids = result.flat_map { |row| row['id'] }
      Vulnerabilities::IssueLink.id_in(ids)
    end
  end
end
